#include "msgqueue.h"
#include "cmsis_os.h"
#include "osapi.h"

MsgQueueImpl::MsgQueueImpl()
{
}

MsgQueueImpl::~MsgQueueImpl()
{
}

void MsgQueueImpl::Create(uint32_t max, uint32_t itemSize)
{
    CreateQ(max, itemSize);
}

bool MsgQueueImpl::Post(void *data, int timeout)
{
    if(timeout == -1)
    {
        timeout = osWaitForever;
    }
    
    //如果是IRQ，timeout不能大于0
    if(OsApi::IsIRQ())
    {
        timeout = 0;
    }

    return osMessageQueuePut(m_qHandle, data, 0, timeout) == osOK;
}

bool MsgQueueImpl::Wait(void *data, int timeout)
{
    if(timeout == -1)
    {
        timeout = osWaitForever;
    }

    return osMessageQueueGet(m_qHandle, data, 0, timeout) == osOK;
}

void MsgQueueImpl::Clear()
{
    osMessageQueueReset(m_qHandle);
}

int MsgQueueImpl::GetCount()
{
    return osMessageQueueGetCount(m_qHandle);
}

int MsgQueueImpl::GetSpace()
{
    return osMessageQueueGetSpace(m_qHandle);
}

int MsgQueueImpl::GetCapacity()
{
    return osMessageQueueGetCapacity(m_qHandle);
}

void MsgQueueImpl::CreateQ(uint32_t max, uint32_t itemSize)
{
    if(max == 0)
    {
        max = 1;
    }
    
    if(itemSize <= 0)
    {
        itemSize = 1;
    }

    osMessageQueueAttr_t attr = {0};
    attr.name = "msgqueue";
    m_qHandle = osMessageQueueNew(max, itemSize, &attr);
}

void MsgQueueImpl::DeleteQ()
{
    osMessageQueueDelete(m_qHandle);
}
